package com.dayaokeji.rhythmschoolstudent.client.mine.account;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.dayaokeji.rhythmschoolstudent.R;
import com.dayaokeji.rhythmschoolstudent.client.common.ActivityStackManager;
import com.dayaokeji.rhythmschoolstudent.client.common.base.Constant;
import com.dayaokeji.rhythmschoolstudent.client.common.base.common.BaseActivity;
import com.dayaokeji.rhythmschoolstudent.client.main.MainActivity;
import com.dayaokeji.rhythmschoolstudent.client.mine.account.bean.RemoteHostPicker;
import com.dayaokeji.rhythmschoolstudent.databases.dao.UserInfoDao;
import com.dayaokeji.rhythmschoolstudent.event.UpdateCourseEvent;
import com.dayaokeji.rhythmschoolstudent.utils.AndroidUtils;
import com.dayaokeji.rhythmschoolstudent.utils.InputUtils;
import com.dayaokeji.rhythmschoolstudent.utils.JPushAliasUtils;
import com.dayaokeji.rhythmschoolstudent.utils.PrefUtils;
import com.dayaokeji.rhythmschoolstudent.utils.RemoteHostUtil;
import com.dayaokeji.rhythmschoolstudent.utils.ServerCallback;
import com.dayaokeji.rhythmschoolstudent.utils.ToastUtils;
import com.dayaokeji.rhythmschoolstudent.utils.UserUtils;
import com.dayaokeji.server_api.ApiUtils;
import com.dayaokeji.server_api.ServerResponse;
import com.dayaokeji.server_api.api.SystemApi;
import com.dayaokeji.server_api.api.UserApi;
import com.dayaokeji.server_api.domain.RemoteHost;
import com.dayaokeji.server_api.domain.UserInfo;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import me.jessyan.retrofiturlmanager.RetrofitUrlManager;
import retrofit2.Call;

/**
 * 手机号码登陆
 */

public class MobileLoginActivity extends BaseActivity {


    @BindView(R.id.et_name)
    EditText etName;
    @BindView(R.id.et_password)
    EditText etPassword;
    @BindView(R.id.btn_login)
    Button btnLogin;
    @BindView(R.id.tv_choose_school_name)
    TextView tvChooseSchoolName;
    @BindView(R.id.iv_select_school_allow)
    ImageView ivSelectSchoolAllow;

    private Call<ServerResponse<UserInfo>> loginCall;
    private static final SystemApi systemApi  = ApiUtils.getApi(SystemApi.class);
    private Call<ServerResponse<List<RemoteHost>>> remoteHostCall;

    private final List<RemoteHostPicker> remoteHostPickers = new ArrayList<>();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTranslucentStatusEnabled(true);
        setContentView(R.layout.activity_mobile_login);

        init();
    }

    private void init() {
        requestRemoteHost();
        setLastName();

    }

    private void setLastName() {
        String lastUserName = PrefUtils.getLastUserName();
        if (!TextUtils.isEmpty(lastUserName)) {
            etName.setText(lastUserName);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        setLastName();
    }

    @OnClick({
            R.id.btn_login,
            R.id.tv_go_register,
            R.id.tv_forget_password,
            R.id.ll_choose_school
    })
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_login:
                login();
                break;
            case R.id.tv_go_register:
                goRegister();
                break;
            case R.id.tv_forget_password:
                goForgetPassword();
                break;
            case R.id.ll_choose_school:
                showChooseSchoolDialog();
                break;
        }
    }

    private void requestRemoteHost() {
        remoteHostPickers.clear();
        remoteHostCall = systemApi.remoteHost();
        remoteHostCall.enqueue(new ServerCallback<List<RemoteHost>>() {
            @Override
            public void onResponse(boolean success, ServerResponse<List<RemoteHost>> response) {
                if (success) {
                    if (success) {
                        if (!MobileLoginActivity.this.isFinishing()) {
                            final List<RemoteHost> body = response.getBody();
                            for (RemoteHost remoteHost : body) {
                                RemoteHostPicker picker = new RemoteHostPicker();
                                picker.setHost(remoteHost.getHost());
                                picker.setName(remoteHost.getName());
                                remoteHostPickers.add(picker);
                            }
                            RemoteHostPicker currentRemoteHost = RemoteHostUtil.getCurrentRemoteHost();
                            if (remoteHostPickers.size() > 0 && currentRemoteHost == null) {
                                RemoteHostPicker remoteHostPicker = remoteHostPickers.get(0);
                                tvChooseSchoolName.setText(remoteHostPicker.getName());
                                tvChooseSchoolName.setTag(remoteHostPicker.getId());
                                RetrofitUrlManager.getInstance().setGlobalDomain(remoteHostPicker.getHost());
                            }else{
                                if (!TextUtils.isEmpty(currentRemoteHost.getHost())) {
                                    tvChooseSchoolName.setText(currentRemoteHost.getName());
                                    tvChooseSchoolName.setTag(currentRemoteHost.getId());
                                    RetrofitUrlManager.getInstance().setGlobalDomain(currentRemoteHost.getHost());
                                }else{
                                    if (remoteHostPickers.size() > 0) {
                                        RemoteHostPicker remoteHostPicker = remoteHostPickers.get(0);
                                        tvChooseSchoolName.setText(remoteHostPicker.getName());
                                        tvChooseSchoolName.setTag(remoteHostPicker.getId());
                                        RetrofitUrlManager.getInstance().setGlobalDomain(remoteHostPicker.getHost());
                                    }
                                }
                            }
                        }
                    }else{
                        ToastUtils.warning("获取学校域名列表失败");
                    }
                }
            }
        });
    }

    private void showChooseSchoolDialog() {
        AndroidUtils.hideSoftInput(getWindow());
        if (remoteHostPickers.size() > 0) {
            final OptionsPickerView optionsPickerView = new OptionsPickerView.Builder(MobileLoginActivity.this, new OptionsPickerView.OnOptionsSelectListener() {
                @Override
                public void onOptionsSelect(int i, int i1, int i2, View view) {
                    RemoteHostPicker remoteHostPicker = remoteHostPickers.get(i);
                    tvChooseSchoolName.setText(remoteHostPicker.getName());
                    tvChooseSchoolName.setTag(remoteHostPicker.getId());
                    RetrofitUrlManager.getInstance().setGlobalDomain(remoteHostPicker.getHost());
                    RemoteHostUtil.saveCurrentRemoteHost(remoteHostPicker);
                }
            }).setTitleText("请选择学校").build();
            optionsPickerView.setPicker(remoteHostPickers);
            optionsPickerView.show();
        }else{
            ToastUtils.warning("没有获取到学校数据，请重试！");
            requestRemoteHost();
        }
    }


    private void login() {

        if (InputUtils.validateInput(etName, "请输入用户名") && InputUtils.validateInput(etPassword, "请输入登录密码")) {
            final String userName = etName.getText().toString().trim();
            final String password = etPassword.getText().toString().trim();
            HashMap<String, String> params = new HashMap<>();
            params.put("phone", userName);
            params.put("password", password);
            params.put("universityId", String.valueOf(tvChooseSchoolName.getTag()));
            btnLogin.setText("登录中...");
            loginCall = ApiUtils.getApi(UserApi.class).login(params);
            loginCall.enqueue(new ServerCallback<UserInfo>(this, "登录中...") {
                @Override
                public void onResponse(boolean success, ServerResponse<UserInfo> response) {
                    if (success) {
                        UserInfo userInfo = response.getBody();
                        PrefUtils.setLastUserName(userInfo.getPhone());
                        initUserInfo(userInfo);
                    }
                    if (btnLogin != null) {
                        btnLogin.setText("登录");
                    }
                }

                @Override
                public void onFailure(Call<ServerResponse<UserInfo>> call, Throwable t) {
                    super.onFailure(call, t);
                    if (btnLogin != null) {
                        btnLogin.setText("登录");
                    }
                }
            });

        }
    }

    /**
     * 初始化用户信息，存储用户信息
     *
     * @param userInfo
     */
    private void initUserInfo(UserInfo userInfo) {
        if (!UserUtils.checkIsStudent(this, userInfo)) {
            return;
        }
        UserUtils.setUserInfo(userInfo);
        UserUtils.setAccessToken(userInfo.getToken());
        UserInfoDao.saveUserInfo(userInfo);
        JPushAliasUtils.getInstance().setJPushAlias(this);
        EventBus.getDefault().post(new UpdateCourseEvent());
        startActivity(new Intent(MobileLoginActivity.this, MainActivity.class));
        ActivityStackManager.finish();
    }


    private void goRegister() {
        Intent intent = new Intent(this, VerifyPhoneNumberActivity.class);
        intent.putExtra(VerifyPhoneNumberActivity.EXTRA_VERIFY_TYPE, Constant.MOBILE_VERIFY_TYPE_REGISTER);
        startActivity(intent);
    }

    private void goForgetPassword() {
        Intent intent = new Intent(this, VerifyPhoneNumberActivity.class);
        intent.putExtra(VerifyPhoneNumberActivity.EXTRA_VERIFY_TYPE, Constant.MOBILE_VERIFY_TYPE_FORGET_PASSWORD);
        startActivity(intent);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (loginCall != null) {
            loginCall.cancel();
        }
        if (remoteHostCall != null) {
            remoteHostCall.cancel();
        }
    }
}

